<template>
  <div class="repair-application">
    <div class="header">
      <div class="header-content">
        <router-link class="back-btn" to="/main/wuye/process">
          <i class="el-icon-arrow-left"></i>
          <span>返回</span>
        </router-link>
        <h2 class="page-title">报修申请</h2>
        <div class="header-actions">
          <el-button 
            type="primary" 
            icon="el-icon-document" 
            @click="goToList">
            报修列表
          </el-button>
        </div>
      </div>
    </div>

    <div class="content">
      <el-form :model="formData" ref="form" label-width="120px" class="application-form">
        <el-form-item label="报修编号">
          <el-input v-model="formData.repairNo" disabled></el-input>
        </el-form-item>

        <el-form-item label="报修人">
          <el-input v-model="formData.applicant"></el-input>
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>

        <el-form-item label="报修位置">
          <el-cascader
            v-model="formData.location"
            :options="locationOptions"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择报修位置">
          </el-cascader>
        </el-form-item>

        <el-form-item label="报修类型">
          <el-select v-model="formData.repairType">
            <el-option label="水电维修" value="水电维修"></el-option>
            <el-option label="空调维修" value="空调维修"></el-option>
            <el-option label="门窗维修" value="门窗维修"></el-option>
            <el-option label="家具维修" value="家具维修"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="紧急程度">
          <el-radio-group v-model="formData.urgencyLevel">
            <el-radio label="一般">一般</el-radio>
            <el-radio label="紧急">紧急</el-radio>
            <el-radio label="特急">特急</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="故障描述">
          <el-input type="textarea" v-model="formData.description" rows="4"
            placeholder="请详细描述故障情况"></el-input>
        </el-form-item>

        <el-form-item label="故障图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="期望维修时间">
          <el-date-picker
            v-model="formData.expectedTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="formData.remarks" rows="3"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      submitting: false,
      formData: {
        repairNo: this.generateRepairNo(),
        applicant: '',
        phone: '',
        location: [],
        repairType: '',
        urgencyLevel: '一般',
        description: '',
        expectedTime: [],
        remarks: ''
      },
      locationOptions: [
        {
          value: 'A栋',
          label: 'A栋',
          children: [
            {
              value: '1层',
              label: '1层',
              children: [
                { value: '101', label: '101' },
                { value: '102', label: '102' }
              ]
            },
            {
              value: '2层',
              label: '2层',
              children: [
                { value: '201', label: '201' },
                { value: '202', label: '202' }
              ]
            }
          ]
        },
        {
          value: 'B栋',
          label: 'B栋',
          children: [
            {
              value: '1层',
              label: '1层',
              children: [
                { value: '101', label: '101' },
                { value: '102', label: '102' }
              ]
            }
          ]
        }
      ],
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        applicant: [
          { required: true, message: '请输入报修人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请选择报修位置', trigger: 'change' }
        ],
        repairType: [
          { required: true, message: '请选择报修类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入故障描述', trigger: 'blur' },
          { min: 10, message: '故障描述不能少于10个字符', trigger: 'blur' }
        ],
        expectedTime: [
          { required: true, message: '请选择期望维修时间', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.submitting = true

            const [building, floor, room] = this.formData.location
            const [startTime, endTime] = this.formData.expectedTime

            const submitData = {
              ...this.formData,
              locationBuilding: building,
              locationFloor: floor,
              locationRoom: room,
              expectedStartTime: startTime,
              expectedEndTime: endTime,
              imageUrls: this.fileList.map(file => file.url).join(',')
            }

            delete submitData.location
            delete submitData.expectedTime

            const response = await this.$http.post('/api/repair/submit', submitData)
            
            this.$message.success('报修申请提交成功')
            this.$router.push('/main/wuye/process')
          } catch (error) {
            const errorMsg = error.response?.data || '提交失败，请稍后重试'
            this.$message.error(errorMsg)
          } finally {
            this.submitting = false
          }
        } else {
          this.$message.warning('请填写完整的报修信息')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.repairNo = this.generateRepairNo()
      this.formData.location = []
      this.formData.expectedTime = []
      this.formData.urgencyLevel = '一般'
      this.fileList = []
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    generateRepairNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `BX${year}${month}${day}${random}`
    },
    goToList() {
      this.$router.push('/main/wuye/baoxiusq-list')
    }
  }
}
</script>

<style lang="scss" scoped>
.repair-application {
  padding: 20px;

  .header {
    margin-bottom: 20px;
    position: relative;
    text-align: center;

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;

      .back-btn {
        text-decoration: none;
        color: #606266;
        display: flex;
        align-items: center;

        &:hover {
          color: #409EFF;
        }

        i {
          margin-right: 5px;
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
        flex: 1;
        text-align: center;
      }

      .header-actions {
        min-width: 100px; // 确保按钮区域有固定宽度
      }
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style> 
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
        flex: 1;
        text-align: center;
      }

      .header-actions {
        min-width: 100px; // 确保按钮区域有固定宽度
      }
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style> 
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
        flex: 1;
        text-align: center;
      }

      .header-actions {
        min-width: 100px; // 确保按钮区域有固定宽度
      }
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style> 
        }
      }

      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
        flex: 1;
        text-align: center;
      }

      .header-actions {
        min-width: 100px; // 确保按钮区域有固定宽度
      }
    }
  }

  .content {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .application-form {
    max-width: 800px;
    margin: 0 auto;
  }
}